#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "listADT.h"
#define EXIT_FAILURE 1
#define MAX_ERROR 256
#define ERROR_MALLOC -1

typedef struct cliInfo {
	int session;
	int pid;
	int cant;
} sessionInfoT;

void
Error(int code)
{
	char msg[MAX_ERROR+1];
	
	switch(code)
	{
		case ERROR_MALLOC: strcpy(msg, "Error: memory allocation error.\n");
							break;
		
	}
	
	fprintf(stderr, msg);
	
	return;
}

int 
compare( listElementT elem1, listElementT elem2)
{
	if(((sessionInfoT *)elem1)->session > ((sessionInfoT *)elem2)->session)
		return 1;
	else if(((sessionInfoT *)elem1)->session == ((sessionInfoT *)elem2)->session)
		return 0;
	else
		return -1;
}

listElementT
copy(listElementT  elem)
{
	sessionInfoT * ret, * aux;
	
	if((ret = malloc(sizeof(sessionInfoT))) == NULL)
	{
		Error(ERROR_MALLOC);
		return NULL;
	}
	aux = (sessionInfoT *) elem;
	ret->session = aux->session;
	ret->pid = aux->pid;
	
	return ret;
}

void
freeNode(listElementT  elem)
{
	free((sessionInfoT *)elem);
}

void
printElement(sessionInfoT * elem)
{
	printf("Session: %d\nPID: %d\n", elem->session, elem->pid);
}

int
main(void)
{
	listADT list;
	sessionInfoT * element;
	int i, j;
	
	if((list = listNew(compare, copy, freeNode)) == NULL)
	{
		fprintf(stderr, "Can't create new list for server information.\n");
		exit(EXIT_FAILURE);
	}
	
	for(i = 0, j=10; i < 10; i++,j++)
	{
		if((element = malloc(sizeof(sessionInfoT))) == NULL)
		{
			Error(ERROR_MALLOC);
			exit(1);
		}

		element->pid = i+j;
		//sleep(1);
		element->session = i;

		if(!listInsert(list, element))
		{
			fprintf(stderr, " i = %d\nCan't insert new list element.\n", i);
			return -1;
		}
		
	}
	
	element->session = 6;
	if((element = GetDatoComp(list, element)) == NULL)
		fprintf(stderr, "Pequenio problema, no lo encontro");
	else
		printElement(element);

//	ToBegin(list);
//	while((element = (sessionInfoT *) GetDato(list)) != NULL)
//		printElement(element);
	
	listFree(list);
	return 1;
	
}
